﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace SMS.Common.ServiceModel
{
    /// <summary>
    /// 利用单例模式和简单工厂模式，根据泛型生成相应接口的实例化对象
    /// </summary>
    public sealed class ServicesFactory
    {
        private static readonly ServicesFactory instance = new ServicesFactory();
        private static readonly ICache cache = new HttpMemoryCache();
        public static ServicesFactory Instance
        {
            get
            {
                return instance;
            }
        }

        private ServicesFactory() { }

        /// <summary>
        /// 根据接口,实例化对象
        /// 先查找缓存,如果不存在就从程序集中加载对象
        /// </summary>
        /// <typeparam name="TService">接口类型</typeparam>
        /// <returns>返回接口的实例对象</returns>
        public TService GetService<TService>() where TService : class
        {
            string interfaceName = typeof(TService).FullName;

            TService t = cache.GetCache<TService>(interfaceName);
            if (t == null)
            {
                //Assembly assembly = Assembly.GetExecutingAssembly();
                var assembly = Assembly.GetAssembly(typeof(TService));
                foreach (var item in assembly.GetTypes())
                {
                    var instance = item.GetInterface(interfaceName);
                    if (instance != null && instance.FullName == interfaceName)
                    {
                        var obj = assembly.CreateInstance(item.FullName);
                        if (obj != null)
                        {
                            cache.SaveToCatche(interfaceName, obj);
                            return obj as TService;
                        }
                    }
                }
                throw new ArgumentNullException("没有找到实现" + interfaceName + "接口的类!");
            }
            else
                return t;
        }
    }
}
